<template>
  <div class="pdf-viewer-container">
    <!-- 控制栏 -->
    <div class="pdf-controls" v-if="showControls">
      <button @click="prevPage" :disabled="pageNumber <= 1">上一页</button>
      <span>第 {{ pageNumber }} 页 / 共 {{ numPages }} 页</span>
      <button @click="nextPage" :disabled="pageNumber >= numPages">下一页</button>
      <select v-model="scale" @change="renderPage">
        <option value="0.5">50%</option>
        <option value="0.75">75%</option>
        <option value="1" selected>100%</option>
        <option value="1.25">125%</option>
        <option value="1.5">150%</option>
        <option value="2">200%</option>
      </select>
    </div>

    <!-- 渲染区域 -->
    <div class="pdf-render-container">
      <canvas ref="pdfCanvas"></canvas>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="pdf-loading">加载中...</div>
    <div v-if="error" class="pdf-error">加载失败: {{ error }}</div>
  </div>
</template>

<script>
import * as pdfjsLib from 'pdfjs-dist'

export default {
  name: 'PDFViewer',
  props: {
    src: {
      type: String,
      required: true
    },
    showControls: {
      type: Boolean,
      default: true
    },
    initialPage: {
      type: Number,
      default: 1
    },
    initialScale: {
      type: Number,
      default: 1.0
    }
  },
  data() {
    return {
      pdf: null,
      pageNumber: this.initialPage,
      numPages: 0,
      scale: this.initialScale,
      loading: false,
      error: null
    }
  },
  watch: {
    src() {
      this.loadPDF()
    }
  },
  mounted() {
    this.initPDFJS()
    this.loadPDF()
  },
  methods: {
    initPDFJS() {
      // 设置 worker 路径（确保 public 目录下有 pdf.worker.js）
      pdfjsLib.GlobalWorkerOptions.workerSrc =
        process.env.NODE_ENV === 'production'
          ? `${process.env.BASE_URL}pdf.worker.js`
          : '/pdf.worker.js'
    },
    async loadPDF() {
      this.loading = true
      this.error = null

      try {
        // 清理之前的 PDF
        if (this.pdf) {
          this.pdf.destroy()
        }

        // 加载新 PDF
        const loadingTask = pdfjsLib.getDocument({
          url: this.src,
          withCredentials: false // 如果需要携带凭证
        })

        this.pdf = await loadingTask.promise
        this.numPages = this.pdf.numPages
        this.pageNumber = Math.min(this.initialPage, this.numPages)

        await this.renderPage()
      } catch (err) {
        console.error('PDF加载失败:', err)
        this.error = err.message || '无法加载PDF文件'
      } finally {
        this.loading = false
      }
    },
    async renderPage() {
      if (!this.pdf) return

      try {
        const page = await this.pdf.getPage(this.pageNumber)
        const viewport = page.getViewport({ scale: this.scale })
        const canvas = this.$refs.pdfCanvas
        const context = canvas.getContext('2d')

        // 调整 canvas 尺寸
        canvas.height = viewport.height
        canvas.width = viewport.width

        // 渲染 PDF 页面
        await page.render({
          canvasContext: context,
          viewport: viewport
        }).promise
      } catch (err) {
        console.error('PDF渲染失败:', err)
        this.error = '渲染PDF页面失败'
      }
    },
    prevPage() {
      if (this.pageNumber > 1) {
        this.pageNumber--
        this.renderPage()
      }
    },
    nextPage() {
      if (this.pageNumber < this.numPages) {
        this.pageNumber++
        this.renderPage()
      }
    }
  },
  beforeDestroy() {
    if (this.pdf) {
      this.pdf.destroy()
    }
  }
}
</script>

<style scoped>
.pdf-viewer-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.pdf-controls {
  padding: 8px;
  background: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.pdf-controls button {
  padding: 4px 8px;
  cursor: pointer;
}

.pdf-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pdf-render-container {
  flex: 1;
  overflow: auto;
  display: flex;
  justify-content: center;
  background-color: #525659;
}

canvas {
  margin: 10px auto;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
}

.pdf-loading, .pdf-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.pdf-error {
  color: red;
}
</style>
